<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    
    <!--  卡片区-->
    <el-card>
      <!--      商品提示信息-->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!--     步骤条-->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!--      tab栏切换-->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          style="height: 550px;"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="addProps"
                expand-trigger="hover"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="动态参数" name="1">
            <el-form-item
              :label="item.attr_name"
              prop="name"
              v-for="item in tabManyData"
              :key="item.attr_id"
            ></el-form-item>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in tabOnlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action表示文件上传的路径 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <!-- 图片预览对话框 -->
            <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
              <img :src="perviewPath" alt class="previewImg">
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
  import _ from "lodash";

  export default {
    name: "Add",
    data() {
      return {
        //当前完成到第几步了
        activeIndex: 0,
        //添加商品表单
        addForm: {
          goods_name: "",
          goods_price: "",
          goods_number: "",
          goods_weight: "",
          goods_cat: [],
          //存放图片数组
          pics: [],
          goods_introduce: "",
          //参数名称
          attrs: []

        },
        //验证规则
        addFormRules: {
          goods_name: [
            {required: true, message: "请输入活动名称", trigger: "blur"},
            {min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur"}
          ],
          goods_price: [
            {required: true, message: "请输入活动名称", trigger: "blur"},
            {min: 1, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur"}
          ],
          goods_number: [
            {required: true, message: "请输入活动名称", trigger: "blur"},
            {min: 1, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur"}
          ],
          goods_weight: [
            {required: true, message: "请输入活动名称", trigger: "blur"},
            {min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur"}
          ]
        },
        //商品分类数据
        cateList: [],
        //级联选择器
        selectedKeys: [],
        //级联选择器配置对象
        addProps: {
          value: "cat_id",
          label: "cat_name",
          children: "children"
        },
        //动态参数列表
        tabManyData: [],
        //静态属性列表
        tabOnlyData: [],
        //给图片上传组件设置一个请求头token
        headerObj: {
          Authorization: window.sessionStorage.getItem("token")
        },
        //文件上传路径
        uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
        //图片预览路径
        perviewPath: "",
        dialogVisible: false
      };
    },
    created() {
      this.getCateList();
    },
    methods: {
      //获取商品分类列表
      async getCateList() {
        let {data: res} = await this.$http.get("categories");
        if (res.meta.status !== 200) this.$message.error("获取商品分类数据失败");
        this.$message.success("获取商品分类数据成功");
        this.cateList = res.data;
        // console.log(this.cateList)
      },
      //级联选择器改变时触发
      handleChange() {
        console.log(this.addForm.goods_cat);
        if (this.addForm.goods_cat.length !== 3) {
          this.addForm.goods_cat = [];
        }
      },
      //tab发生切换时
      beforeTabLeave(activeName, oldActiveName) {
        // console.log(activeName, oldActiveName)
        //如果没有选中分类时,不允许切换tab栏
        if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
          this.$message.error("请先选择商品分类");
          return false;
        }
      },
      //切换到动态参数时触发
      async tabClicked() {
        if (this.activeIndex === "1") {
          //说明切换到的是动态参数
          let {data: res} = await this.$http.get(
            `categories/${this.cateId}/attributes`,
            {
              params: {
                sel: "many"
              }
            }
          );
          console.log(res.data);
          if (res.meta.status !== 200) {
            return this.$message.error("获取动态参数失败");
          }
          res.data.forEach(item => {
            item.attr_vals =
              item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
          });
          this.tabManyData = res.data;
          // console.log(this.tabManyData)
        } else if (this.activeIndex === "2") {
          let {data: res} = await this.$http.get(
            `categories/${this.cateId}/attributes`,
            {
              params: {
                sel: "only"
              }
            }
          );
          console.log(res.data);
          if (res.meta.status !== 200) {
            return this.$message.error("获取动态参数失败");
          }
          this.tabOnlyData = res.data;
        }
      },
      //图片预览的操作
      handlePreview(file) {
        console.log(file);
        //路径赋值给预览的路径
        this.perviewPath = file.response.data.url;
        this.dialogVisible = true;
      },
      //图片删除的操作
      handleRemove(file) {
        // console.log(file);
        //1.先获取图片的临时路径
        let filePath = file.response.data.tem_path;
        //2.从数组中查出要删除的图片的索引
        let index = this.addForm.findIndex(item => {
          item.pic = filePath;
        });
        //3.然后从数组中删除
        this.addForm.pics.splice(index, 1);
      },
      //图片上传成功
      handleSuccess(res) {
        // console.log(res);
        //1.创建一个图片信息对象
        let imageInfo = {pic: res.data.tem_path};
        this.addForm.pics.push(imageInfo);
      },
      //添加商品
      add() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) {
            return this.$message.error("请填写必要的表单数据");
          }
          //完成验证通过之后的逻辑
          let form = _.cloneDeep(this.addForm);
          form.goods_cat = form.goods_cat.join(",");
          console.log(form)
          //处理动态参数
          this.tabManyData.forEach(item => {
            let userInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(' ')
            }
            //放到数组里面去
            this.addForm.attrs.push(userInfo)
          }),
            //处理静态参数
            this.tabOnlyData.forEach(item => {
              let userInfo = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals
              }
              this.addForm.attrs.push(userInfo)
            })
          form.attrs = this.addForm.attrs
          console.log(form)
          //发送请求
          let {data: res} = await this.$http.post(`goods`, form)
          if (res.meta.status !== 201) return this.$message.error('添加商品失败')
          this.$message.success('添加商品成功')
          this.$router.push('/goods')
        });
      }
    },
    //分类id
    computed: {
      //级联选择器三级分类ID
      cateId() {
        if (this.addForm.goods_cat.length === 3) {
          return this.addForm.goods_cat[2];
        }
        return null;
      }
    }
  };
</script>

<style scoped lang="less">
  .el-steps {
    margin-top: 20px;
  }
  
  .el-step__title {
    font-size: 13px;
  }
  
  .el-tabs {
    margin-top: 20px;
  }
  
  .previewImg {
    width: 100%;
  }
</style>
